<!-- 用户管理 -->
<template>
  <div class="app-container">
    <!-- <div style="width: 100px; height: 100px; background-color: aqua"></div> -->
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <el-card shadow="never" class="elTree">
          <div class="client">
            <div class="list">
              <el-icon style="margin-right: 5px" size="20">
                <UserFilled />
              </el-icon>
              门店管理
            </div>
            <el-button type="primary" size="small" @click="handleOpenDialog('none')">添加</el-button>
          </div>
          <dept-tree :currentNodeKey="clientID" ref="DeptTrees" v-model="queryParams.customerId"
            @node-click="handleQuery" @node-contextmenu="contextmenuClick" />
        </el-card>

      </el-col>

      <!-- 用户列表 -->
      <el-col :lg="20" :xs="24">
        <el-card shadow="never" class="table-container">
          <!-- <div class="flex-between">
            <div class="btnLeft">
              <div class="btn" @click="menuSelect(1)" :class="active === 1 ? 'active' : ''">
                全部
              </div>
              <div class="btn" @click="menuSelect(2)" :class="active === 2 ? 'active' : ''">
                到期设备
              </div>
              <div class="btn" @click="menuSelect(3)" :class="active === 3 ? 'active' : ''">
                离线设备
              </div>
            </div>
          </div> -->
          <all-device @handleOpenDialog="handleOpenDialogALL" ref="AllchildRef" v-if="active === 1"
            :customerId="queryParams.customerId" />
          <dept-maturity v-else-if="active === 2" />
          <dept-offline v-else-if="active === 3" />
        </el-card>
      </el-col>
    </el-row>

    <!--右键显示的菜单组件-->
    <div v-show="treeRightMenuShow" class="tree_rightmenu" :style="{ ...rightTreeMenuStyle }">
      <div class="tree_rightmenu_item" @click="refresh">刷新</div>
      <div class="tree_rightmenu_item" @click="handleOpenDialog()">新增客户</div>
      <div class="tree_rightmenu_item" v-if="rightTreeMenuStyle.level != 1" @click="handleOpenDialog('edit')">管理客户</div>
      <div class="tree_rightmenu_item" v-if="rightTreeMenuStyle.level != 1" @click="deletecustomer">删除客户</div>
      <!-- <div class="tree_rightmenu_item" v-if="rightTreeMenuStyle.level != 1" @click="resetPsw">重置密码</div> -->
      <!-- <div class="tree_rightmenu_item" v-if="rightTreeMenuStyle.level != 1" @click="updatecustomer">转移客户</div> -->
      <!-- <div class="tree_rightmenu_item" @click="updatedevice">转入设备</div> -->
    </div>
    <el-drawer v-model="dialog.visible" :title="dialog.title" width="80vw" @close="handleCloseDialog">
      <div class="div-container">
        <el-form ref="userFormRef" :model="formData" :rules="deviceRules" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" :disabled="dialog.title == '编辑客户'" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="dialog.title !== '编辑客户'">
            <el-input v-model="formData.password" placeholder="请输入密码" maxlength="11" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="身份证号码" prop="idCardNo">
            <el-input v-model="formData.idCardNo" placeholder="请输入身份证号码" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入手机号" />
          </el-form-item>
          <!-- <el-form-item label="所属客户" prop="contact.customerId">
            <el-tree-select v-model="formData.contact.customerId" placeholder="请选择所属客户"
              :props="{ children: 'children', label: 'customerName', value: 'id' }" :data="deptOptions" filterable
              check-strictly :render-after-expand="false" />
          </el-form-item> -->
          <el-form-item label="角色" prop="roleIdList">
            <el-select v-model="formData.roleIdList" multiple placeholder="请选择">
              <el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
                :value="item.value ? item.value : ''" />
            </el-select>
          </el-form-item>
          <el-form-item label="商店名称" prop="storeName">
            <el-input v-model="formData.storeName" placeholder="请输入商店名称" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="地址经纬度">
            <el-input v-model="formData.lat" placeholder="请获取纬度" style="width: 100px;" />
            <el-input v-model="formData.lng" placeholder="请获取经度" style="width: 100px; margin-left: 10px;" />
          </el-form-item>
          <el-form-item label="其他" prop="other">
            <el-input v-model="formData.other" placeholder="请输入(qq/邮箱/微信)" maxlength="11" />
          </el-form-item>

          <el-form-item label="用户状态">
            <el-radio-group v-model="formData.userEnableFlag">
              <el-radio value="ENABLE">正常</el-radio>
              <el-radio value="DISABLE">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="店铺状态">
            <el-radio-group v-model="formData.storeEnableFlag">
              <el-radio value="ENABLE">正常</el-radio>
              <el-radio value="DISABLE">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">

          <el-button type="info" @click="dialog.visible = false">
            取消
          </el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
    <el-dialog v-model="updateshow" title="转移客户" width="500">
      <div>
        <el-cascader :options="treeList" clearable @change="changetree" :props="defaultProps" />
      </div>
      <div style="width: 100%;text-align: center;margin-top: 10px">
        <el-button type="primary" @click="updatesubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="updatedeviceshow" title="转入设备" width="500">
      <div>


      </div>
      <div style="width: 100%;text-align: center;margin-top: 10px">
        <el-button type="primary" @click="devicesubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "deviceManagement",
  inheritAttrs: false,
});
import DeviceApi, { distributeDevice } from "@/api/device"

import AllDevice from "./component/All.vue";
import DeptMaturity from "./component/maturity.vue";
import DeptOffline from "./component/offline.vue";
import DeviceManagementApi, { ManagementPage, ManagementPageList } from "@/api/deviceManagement"

import UserAPI, { UserPageQuery } from "@/api/user";
import CustomerAPI, { } from "@/api/customer";
import RoleAPI from "@/api/role";
import StoreeApi, { RuleForm } from "@/api/store"


import { useRoute } from 'vue-router'

const route = useRoute()

const DeptTrees = ref<any>()
// 转入设备弹出层

let updatedeviceshow = ref(false);
interface devicetype {
  id: string;
  device_name: string;
}
let devicelist = ref<devicetype[]>([])
let devicevalue = ref('')




// 转移客户弹出层
let filters = reactive<ManagementPage>({
  "pages": {
    "current": 1,
    "size": 10,
    "total": 0,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  // deviceStatus:'',
  // onlineStatus:'',
  // expireStatus:'',
  deviceTypeId: '',
  customerId: '',
  isChild: true
});
let updateshow = ref(false);
const defaultProps = {

  checkStrictly: true,
  value: "id",
  label: "customerName",
  children: "children"
}

/**
@date: 2024-08-29 11:15:19
右键控制菜单是否隐藏
*/
let treeRightMenuShow = ref(false);
/**
@date: 2024-08-29 11:14:51
右键菜单的样式
*/
let rightTreeMenuStyle = ref({
  top: '',
  left: '',
  level: 0
});
/**
@date: 2024-08-29 11:14:22
用户高亮
*/
let active = ref(1);
/**
@date: 2024-09-21 10:48:04
表单数据
*/
const userFormRef = ref(ElForm);

const formData = reactive<RuleForm>(
  {
    "userId": undefined,
    "username": "",
    "password": undefined,
    "idCardNo": "",
    "userEnableFlag": "ENABLE",
    "roleIdList": [],
    "other": "",
    "storeId": undefined,
    "parentId": undefined,
    "storeName": "",
    "address": "",
    "lng": '',
    "lat": '',
    "storeEnableFlag": "ENABLE",
    "name": "",
    "phone": "",
    "customerId": undefined
  }
)
const deviceRules = reactive({
  'customer.customerName': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  'contact.name': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  'contact.username': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  'contact.password': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  // 'contact.customerId': [
  //   { required: true, message: '不能为空', trigger: 'change' },
  // ],
  'contact.roleIdList': [
    { required: true, message: '不能为空', trigger: 'change' },
  ],
  'contact.phone': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],


})
/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});
const loading = ref(false);

/** 部门下拉选项 */
const deptOptions = ref<OptionType[]>();
/** 角色下拉选项 */
const roleOptions = ref<OptionType[]>();

/** 用户查询参数  */
const queryParams = reactive<UserPageQuery>({
  "pages": {
    "current": 1,
    "size": 10,
    "total": 0,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  customerId: ""
});

const AllchildRef = ref<any>(null);
/** 查询 */
function handleQuery() {
  let value = AllchildRef.value.getpageType
  console.log(value, queryParams.customerId);

  if (value == 1) {

    AllchildRef.value.getManagementPage();
    AllchildRef.value.storeInformation();

  } else {

    AllchildRef.value.getSubCustomer(queryParams.customerId);

  }
  // AllchildRef.value.getManagementPage();
}
/**
 鼠标右键 
 */
let fatherID = ref()
let fatherName = ref()
function contextmenuClick(event: any, data: any, node: any) {
  treeRightMenuShow.value = true;
  formData.parentId = data.value//本身id

  // formData.customerName = data.customerName//本身id
  // fatherID.value = data.parentId//父id
  fatherName.value = data.label//父id


  //防止右键菜单底部被覆盖 --可以自己根据右键菜单的高度调整
  let jianPx = 0;
  if (document.documentElement.clientHeight - event.pageY < 200) {
    jianPx = 200;
  }
  //右键菜单的位置
  rightTreeMenuStyle.value = {
    top: event.pageY - jianPx + "px",
    left: event.pageX + "px",
    level: node.level,
  };

  //点击页面其他地方关闭右键菜单
  document.addEventListener("click", (ev) => {
    hideRightMenu();
  });
}

function refresh() {
  DeptTrees.value.getCustomerTree()
}

function hideRightMenu() {
  treeRightMenuShow.value = false;
  //关闭点击页面其他地方关闭右键菜单的监听
  document.removeEventListener("click", hideRightMenu);
}
function menuSelect(data: number) {
  active.value = data;
}

// 删除客户
function deletecustomer() {
  // let data={
  // ${formData.customer.fatherName}
  let id = formData.parentId as string
  ElMessageBox.confirm(`确认删除 "${fatherName.value}"?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      StoreeApi.deletecustomer(id).then(() => {
        ElMessage.success("删除成功");
        refresh()
      })
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );

}
// 重置密码
function resetPsw() {
  // ${formData.customerName}
  ElMessageBox.confirm(`确认重置 "" 密码?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      let customerId = formData.parentId as string
      UserAPI.resetPassword(customerId).then(() => {
        ElMessage.success("删除成功");
      })

    },
    () => {
      ElMessage.info("已取消重置");
    }
  );
}

// 转入设备
function updatedevice() {
  updatedeviceshow.value = true
  devicevalue.value = ''
  devicelist.value = []
  DeviceManagementApi.getManagementPage(filters)
    .then((data) => {
      devicelist = data.data.records
    })
}

// 转移客户弹出层
let treeList = reactive<OptionType[]>([])
let pid = ref('')
function changetree(value: any) {
  console.log(value.length, '===', value);
  pid.value = value[value.length - 1]

}
function updatecustomer() {
  updateshow.value = true
  treeList.length = 0
  CustomerAPI.getCustomerTree().then((res) => {
    treeList.push(res)

  })

}
// 转入设备选择
let seldevice = ref([])
function changesel(data: any) {
  console.log(data);
  seldevice.value = data
}

function devicesubmit() {
  // console.log(data,devicevalue);
  const childComponent = AllchildRef.value.seldata;
  console.log(childComponent, '000');
  if (childComponent.length <= 0) {
    ElMessage({
      message: '请先选择要转入的设备',
      type: 'warning',
    })
  } else {

    let result = [];
    for (const item of childComponent) {
      result.push(item.id);
    }
    // `${formData.customer.parentId}`
    let data = {
      customerId: '',
      deviceId: result
    }
    DeviceApi.BatchAllocate(data).then((res) => {
      ElMessage({
        message: '配对成功',
        type: 'success',
      })
      updatedeviceshow.value = false
      AllchildRef.value.getManagementPage();

    })
  }

}
//转移客户提交按钮 
function updatesubmit() {
  let data = {

    parentId: pid.value,
    id: formData.parentId as string
  }
  console.log(data, 'daaaaa');

  if (data.parentId !== data.id) {
    CustomerAPI.updatecustomer(data).then((res) => {
      refresh();
      updateshow.value = false;

      ElMessage({
        message: '转移客户成功',
        type: 'success',
      });
    }).catch((error) => {
      ElMessage({
        message: '转移客户失败',
        type: 'error',
      });
    });
  } else {
    console.log('parentId 和 id 相同，接口请求未执行');
    ElMessage({
      message: '转移客户失败,请选择其他客户在进行转移',
      type: 'warning',
    });
  }
}
/**
 * 打开弹窗
 *
 */
async function handleOpenDialog(code?: string, id?: string, enableFlag?: string) {
  if (!enableFlag) {
    dialog.visible = true;
  }

  // 加载角色下拉数据源
  roleOptions.value = await RoleAPI.getOptions();
  // // 加载部门下拉数据源
  // deptOptions.value = []
  // deptOptions.value.push(await CustomerAPI.getCustomerTree())

  if (code && code !== 'none') {
    console.log(6666666, code);

    dialog.title = "编辑客户";
    console.log('xinzeng', code, formData);

    StoreeApi.getselectCustomerAndContact(id ? id : formData.parentId as string).then((data) => {
      // const { createTime, ...rest } = data;
      Object.assign(formData, data);
    });
  } else {
    if (code == 'none') {
      formData.username = ''
      formData.parentId = queryParams.customerId
    } else {
      formData.userEnableFlag = 'ENABLE'
      formData.storeName = ''
    }

    dialog.title = "新增客户";
  }
}

// function restform(){
//   formData.contact={}

// }
/** 表单提交 */
const handleSubmit = useThrottleFn(() => {

  userFormRef.value.validate((valid: any) => {
    if (valid) {

      loading.value = true;
      if (dialog.title === '编辑客户') {

        StoreeApi.upCustomer(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            dialog.visible = false;
          })
          .finally(() => (loading.value = false));
      } else {
        StoreeApi.addCustomer(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            dialog.visible = false;
            refresh()
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);
const clientID = ref('')
watch(
  () => route.query.clientID,
  (newId, oldId) => {
    console.log(`路由参数 id 变化了: 从 ${oldId} 变为 ${newId}`);
    if (route.query.clientID !== '' && route.query.clientID !== undefined) {
      clientID.value = route.query.clientID as string
      queryParams.customerId = route.query.clientID as string
    }
    // 在这里可以进行其他操作，比如重新获取数据等
  }
);
function handleOpenDialogALL(data: any, enableFlag?: string) {
  // formData.customer.enableFlag = enableFlag
  if (enableFlag) {
    var formdata = {
      id: data.id,
      customerName: data.customerName,
      enableFlag: enableFlag
    }
    CustomerAPI.updateCust(formdata)
      .then(() => {
        AllchildRef.value.getSubCustomer();
      })
      .finally(() => (loading.value = false));
  } else {
    handleOpenDialog('edit', data.id, enableFlag)

  }
}
/** 关闭弹窗 */
function handleCloseDialog() {
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.lat = undefined
  formData.lng = undefined
  // formData = reactive<RuleForm>({})
}
onMounted(() => {
  if (route.query.clientID !== '' && route.query.clientID !== undefined) {
    setTimeout(() => {
      clientID.value = route.query.clientID as string
      queryParams.customerId = route.query.clientID as string
      AllchildRef.value.getManagementPage();
    }, 200);
  }
});
</script>
<style lang="scss" scoped>
.tree_rightmenu {
  position: fixed;
  padding: 5px 0;
  margin: 0;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  box-shadow: 2px 2px 8px 0 hsla(0, 0%, 59%, 0.2);
  list-style: none;
  font-size: 14px;
  white-space: nowrap;
  cursor: pointer;

  .tree_rightmenu_item {
    padding: 2px 14px;
    color: #333;

    &:hover {
      background-color: #46a0fc;
      color: #fff;
    }
  }
}

.flex-between {
  display: flex;
  justify-content: space-between;

  .btnLeft {
    display: flex;
    align-items: center;

    .btn {
      padding: 0 12px;
      border-radius: 15px;
      height: 31px;
      line-height: 31px;
      cursor: pointer;
      margin-right: 20px;

      &.active {
        background: linear-gradient(167deg, #5cadff, #2a6cad);
      }
    }
  }

  .cotentRight {
    display: flex;
    align-items: center;

    div {
      margin-left: 26px;
      font-weight: 700;

      span {
        margin-left: 8px;
      }
    }
  }
}

.div-container {
  :deep(.form-container) {
    .el-form-item__label {
      color: #333;
    }

    .el-input__inner {
      color: #333;
    }

    .el-textarea__inner {
      color: #333;

    }
  }
}
</style>
